//
//  ContactViewController.m
//  51易借
//
//  Created by 张睿 on 2017/8/31.
//  Copyright © 2017年 张睿. All rights reserved.
//

#import "ContactViewController.h"
#import "MemberInfoModel.h"
#import "MemberInfoTypePageModel.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "HDAddressBookTool.h"
@import Contacts;

@interface ContactViewController ()<ABPeoplePickerNavigationControllerDelegate>
@property (nonatomic,strong)MemberInfoTypePageModel * typePageModel;
@property (nonatomic,copy)void(^selectBlock)(NSString*tel,NSString*number);
@property (nonatomic, weak)UIView * topView;
@property (nonatomic, weak)UILabel * topLabel;
@property (nonatomic, weak)UIView * topInputView;
@property (nonatomic, strong)UILabel * relationLabel;
@property (nonatomic, strong)UIButton * relationButton;
@property (nonatomic, strong)UIImageView * relationRightImageView;
@property (nonatomic,strong)UITextField * relationField;
@property (nonatomic,strong)UITextField * bottomRelationField;
@property (nonatomic,strong)UITextField * contractField;
@property (nonatomic,strong)UITextField * bottonContractField;
@property (nonatomic, strong)UIView * oneLineView;
@property (nonatomic, strong)UILabel * contactLabel;
@property (nonatomic, strong)UIButton * contactButton;
@property (nonatomic, strong)UIImageView * contactRightImageView;
@property (nonatomic, weak)UILabel * bottomLabel;
@property (nonatomic, weak)UIView * bottomInputView;
@property (nonatomic, strong)UILabel * bottomRelationLabel;
@property (nonatomic, strong)UIButton * bottomRelationButton;
@property (nonatomic, strong)UIImageView * bottomRelationRightImageView;
@property (nonatomic, strong)UIView * twoLineView;
@property (nonatomic, strong)UILabel * bottomContactLabel;
@property (nonatomic, strong)UIButton * bottomContactButton;
@property (nonatomic, strong)UIImageView * bottomContactRightImageView;
@property (nonatomic, weak)UIButton * sureButton;
@property (nonatomic,strong)MemberInfoModel * pageModel;
@property (nonatomic,strong)ParaModel * para;

@property (nonatomic, assign)int count;

@property (nonatomic, strong)UIButton * oneButton;
@property (nonatomic, strong)UIButton * twoButton;
@property (nonatomic, strong)UIButton * threeButton;
@property (nonatomic, strong)UIButton * fourButton;


//@property (nonatomic, copy)NSString * familyContactName;
//@property (nonatomic, copy)NSString * familyContactTel;
//@property (nonatomic, copy)NSString * familyContactType;
//@property (nonatomic, copy)NSString * urgencyContactName;
//@property (nonatomic, copy)NSString * urgencyContactTel;
//@property (nonatomic, copy)NSString * urgencyContactType;


@end

@implementation ContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = BACK_COLOR;
    
//    self.count = 1;
    [self getPageModel];
    [self setupNavBar];
    [self setupUI];
}


- (void)setupNavBar{
    
    self.title = @"紧急联系人";
    
    UIButton * backButton = [[UIButton alloc] init];
    
    backButton.frame = CGRectMake(15 * SCREENH6, 5 * SCREENH6, 12 * SCREENH6, 20 * SCREENH6);
    [backButton setImage:[UIImage imageNamed:@"箭头"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backToLastView) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * leftButton = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}


- (void)setupUI{
    
    UIView * topView = [UIView new];
    
    topView.backgroundColor = TOTAL_COLOR;
    
    self.topView = topView;
    
    [self.view addSubview:self.topView];
    
    
    UILabel * topLabel = [UILabel new];
    
    topLabel.textColor = ColorWithRGB(0x7f7f7f);
    topLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    topLabel.text = @"直系亲属联系人";
    
    self.topLabel = topLabel;
    
    [self.view addSubview:self.topLabel];
    
    
    UIView * topInputView = [UIView new];
    
    topInputView.backgroundColor = [UIColor whiteColor];
    topInputView.layer.borderColor = [ColorWithRGB(0xe6e6e6) CGColor];
    topInputView.layer.borderWidth = 0.5 * SCREENH6;
    
//    if (self.currentStep > 2) {
//       
//        topInputView.userInteractionEnabled = NO;
//    }else{
//        
//        topInputView.userInteractionEnabled = YES;
//    }
    
    self.topInputView = topInputView;
    
    [self.view addSubview:self.topInputView];
    
    
    self.relationLabel = [self setupLabelWith:@"与本人关系"];
    
    [self.topInputView addSubview:self.relationLabel];
    
    
    self.relationField = [self setUpTextfieldWithString:@"请选择"];
    self.relationField.userInteractionEnabled = NO;
    [self.topInputView addSubview:self.relationField];
    
    
    self.relationButton = [self setupTitleButtonWith:@"请选择"];
    self.relationButton.tag = 0;
    [self.topInputView addSubview:self.relationButton];
    
    self.relationRightImageView = [self setupRightImage];
    
    [self.topInputView addSubview:self.relationRightImageView];
    
    self.oneLineView = [self setupLineView];
    
    [self.topInputView addSubview:self.oneLineView];
    
    self.contactLabel = [self setupLabelWith:@"紧急联系人"];
    
    [self.topInputView addSubview:self.contactLabel];
    
    self.contractField = [self setUpTextfieldWithString:@"请选择"];
    self.contractField.userInteractionEnabled = NO;
    [self.topInputView addSubview:self.contractField];
    
    
    self.contactButton = [self setupTitleButtonWith:@"请选择"];
    self.contactButton.tag = 1;

    [self.topInputView addSubview:self.contactButton];
    
    self.contactRightImageView = [self setupRightImage];
    
    [self.topInputView addSubview:self.contactRightImageView];
    
    
    UILabel * bottomLabel = [UILabel new];
    
    bottomLabel.textColor = ColorWithRGB(0x7f7f7f);
    bottomLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    bottomLabel.text = @"常用联系人";
    
    self.bottomLabel = bottomLabel;
    
    [self.view addSubview:self.bottomLabel];
    
    
    UIView * bottomInputView = [UIView new];
    
    bottomInputView.backgroundColor = [UIColor whiteColor];
    bottomInputView.layer.borderColor = [ColorWithRGB(0xe6e6e6) CGColor];
    bottomInputView.layer.borderWidth = 0.5 * SCREENH6;
//    if (self.currentStep > 2) {
//        
//        bottomInputView.userInteractionEnabled = NO;
//    }else{
//        
//        bottomInputView.userInteractionEnabled = YES;
//    }
    
    self.bottomInputView = bottomInputView;
    
    [self.view addSubview:self.bottomInputView];
    
    
    self.bottomRelationLabel = [self setupLabelWith:@"与本人关系"];
    
    [self.bottomInputView addSubview:self.bottomRelationLabel];
    
    self.bottomRelationField = [self setUpTextfieldWithString:@"请选择"];
    self.bottomRelationField.userInteractionEnabled = NO;
    [self.bottomInputView addSubview:self.bottomRelationField];
    
    
    
    self.bottomRelationButton = [self setupTitleButtonWith:@"请选择"];
    self.bottomRelationButton.tag = 2;

    [self.bottomInputView addSubview:self.bottomRelationButton];
    
    self.bottomRelationRightImageView = [self setupRightImage];
    
    [self.bottomInputView addSubview:self.bottomRelationRightImageView];
    
    self.twoLineView = [self setupLineView];
    
    [self.bottomInputView addSubview:self.twoLineView];
    
    self.bottomContactLabel = [self setupLabelWith:@"紧急联系人"];
    
    [self.bottomInputView addSubview:self.bottomContactLabel];
    self.bottonContractField = [self setUpTextfieldWithString:@"请选择"];
    self.bottonContractField.userInteractionEnabled = NO;
    [self.bottomInputView addSubview:self.bottonContractField];
    self.bottomContactButton = [self setupTitleButtonWith:@"请选择"];
    self.bottomContactButton.tag = 3;

    [self.bottomInputView addSubview:self.bottomContactButton];
    
    self.bottomContactRightImageView = [self setupRightImage];
    
    [self.bottomInputView addSubview:self.bottomContactRightImageView];
    
    
    UIButton * sureButton = [UIButton new];
    //300 * 42
    [sureButton setTitle:@"保存" forState:UIControlStateNormal];
    [sureButton setBackgroundImage:[UIImage imageNamed:@"登录"] forState:UIControlStateNormal];
    [sureButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sureButton addTarget:self action:@selector(didSaveButton) forControlEvents:UIControlEventTouchUpInside];
    sureButton.titleLabel.font = [UIFont systemFontOfSize:14 * SCREENH6];
    
//    if (self.currentStep > 2) {
//        
//        sureButton.hidden = YES;
//    }else{
//        
//        sureButton.hidden = NO;
//    }
    
    self.sureButton = sureButton;
    
    [self.view addSubview:self.sureButton];
    
    self.oneButton = [self setBackButton];
    self.oneButton.tag = 0;
    [self.view addSubview:self.oneButton];
    
    self.twoButton = [self setBackButton];
    self.twoButton.tag = 1;
    [self.view addSubview:self.twoButton];
    
    self.threeButton = [self setBackButton];
    self.threeButton.tag = 2;
    [self.view addSubview:self.threeButton];
    
    self.fourButton = [self setBackButton];
    self.fourButton.tag = 3;
    [self.view addSubview:self.fourButton];
}


- (void)viewDidLayoutSubviews{
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.mas_equalTo(self.view);
        make.height.mas_equalTo(64);
    }];
    
    [self.topLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(13 * SCREENH6);
        make.top.mas_equalTo(self.topView.mas_bottom).offset(10 * SCREENH6);
    }];
    
    [self.topInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(10 * SCREENH6);
        make.trailing.mas_equalTo(self.view).offset(-10 * SCREENH6);
        make.height.mas_equalTo(104 * SCREENH6);
        make.top.mas_equalTo(self.topLabel.mas_bottom).offset(7 * SCREENH6);
    }];
    
    [self.relationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topInputView).offset(20 * SCREENH6);
        make.leading.mas_equalTo(self.topInputView).offset(8 * SCREENH6);
    }];
    
    [self.relationRightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.topInputView).offset(-8 * SCREENH6);
        make.width.mas_equalTo(7.5 * SCREENH6);
        make.height.mas_equalTo(12.5 * SCREENH6);
        make.centerY.mas_equalTo(self.relationLabel);
    }];
    [self.relationField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.relationLabel);
        make.trailing.mas_equalTo(self.relationRightImageView.mas_leading).offset(-15 * SCREENH6);
    }];
    
    [self.relationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.relationLabel);
        make.trailing.mas_equalTo(self.relationRightImageView.mas_leading).offset(-15 * SCREENH6);
    }];
    
    [self.oneLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.topInputView).offset(2 * SCREENH6);
        make.trailing.mas_equalTo(self.topInputView).offset(-2 * SCREENH6);
        make.height.mas_equalTo(0.5 * SCREENH6);
        make.top.mas_equalTo(self.topInputView).offset(52 * SCREENH6);
    }];
    
    [self.contactLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.relationLabel);
        make.top.mas_equalTo(self.oneLineView.mas_bottom).offset(18 * SCREENH6);
    }];
    
    [self.contactRightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.width.trailing.mas_equalTo(self.relationRightImageView);
        make.centerY.mas_equalTo(self.contactLabel);
    }];
    [self.contractField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.relationButton);
        make.centerY.mas_equalTo(self.contactLabel);
    }];
    [self.contactButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.relationButton);
        make.centerY.mas_equalTo(self.contactLabel);
    }];
    
    [self.bottomLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.topInputView.mas_bottom).offset(10 * SCREENH6);
        make.leading.mas_equalTo(self.topLabel);
    }];
    
    [self.bottomInputView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.topInputView);
        make.top.mas_equalTo(self.bottomLabel.mas_bottom).offset(7 * SCREENH6);
    }];
    
    [self.bottomRelationLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.contactLabel);
        make.top.mas_equalTo(self.bottomInputView).offset(20 * SCREENH6);
    }];
    
    [self.bottomRelationRightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.height.width.mas_equalTo(self.contactRightImageView);
        make.centerY.mas_equalTo(self.bottomRelationLabel);
    }];
    [self.bottomRelationField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.contactButton);
        make.centerY.mas_equalTo(self.bottomRelationLabel);
    }];
    [self.bottomRelationButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.contactButton);
        make.centerY.mas_equalTo(self.bottomRelationLabel);
    }];
    
    [self.twoLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.height.mas_equalTo(self.oneLineView);
        make.top.mas_equalTo(self.bottomInputView).offset(52 * SCREENH6);
    }];
    
    [self.bottomContactLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.bottomRelationLabel);
        make.top.mas_equalTo(self.twoLineView.mas_bottom).offset(18 * SCREENH6);
    }];
    
    [self.bottomContactRightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.height.width.mas_equalTo(self.bottomRelationRightImageView);
        make.centerY.mas_equalTo(self.bottomContactLabel);
    }];
    [self.bottonContractField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.bottomRelationButton);
        make.centerY.mas_equalTo(self.bottomContactLabel);
    }];
    
    [self.bottomContactButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.bottomRelationButton);
        make.centerY.mas_equalTo(self.bottomContactLabel);
    }];
    
    [self.sureButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.top.mas_equalTo(self.bottomInputView.mas_bottom).offset(60 * SCREENH6);
        make.width.mas_equalTo(300 * SCREENH6);
        make.height.mas_equalTo(42 * SCREENH6);
    }];
    
    [self.oneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.trailing.leading.mas_equalTo(self.topInputView);
        make.bottom.mas_equalTo(self.oneLineView.mas_top);
    }];
    
    [self.twoButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.leading.height.mas_equalTo(self.oneButton);
        make.top.mas_equalTo(self.oneButton.mas_bottom);
    }];
    
    [self.threeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.leading.height.mas_equalTo(self.twoButton);
        make.top.mas_equalTo(self.bottomInputView);
    }];
    
    [self.fourButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.leading.height.mas_equalTo(self.threeButton);
        make.top.mas_equalTo(self.threeButton.mas_bottom);
    }];
    
}



- (void)didSaveButton{
    if(self.relationField.text.length == 0)
    {
        [self showHint:@"请选择直系亲属人关系"];
        return;
    }
    if(self.contractField.text.length == 0)
    {
        [self showHint:@"请选择直系亲属人"];
        return;
    }
    if(self.bottomRelationField.text.length == 0)
    {
        [self showHint:@"请选择直系亲属人关系"];
        return;
    }
    if(self.bottonContractField.text.length == 0)
    {
        [self showHint:@"请选择直系亲属人"];
        return;
    }
    
    [self upLoadAddressBookComplete:^{
    
//        NSDictionary * dict = @{@"familyContactName":@"aaaaa",@"familyContactTel":self.familyContactTel,@"familyContactType":self.familyContactType,@"urgencyContactName":@"bbbbb",@"urgencyContactTel":self.urgencyContactTel,@"urgencyContactType":self.urgencyContactType};
//
//        NSLog(@"dict++%@",dict);
        //[self.para toDictionary]
        
        
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURL * url = [NSURL URLWithString:@"http://api.xianjinedai.com/"];
//        NSURL * url = [NSURL URLWithString:@"http://106.14.157.18:8080/"];
        
        //1.实例化
        AFHTTPSessionManager * instance = [[AFHTTPSessionManager alloc] initWithBaseURL:url sessionConfiguration:configuration];
        
        //2.可接受格式
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"text/plain", nil];
        
        
        //4.超时
        instance.requestSerializer.timeoutInterval = 10.0;
    
     NSString * token = DEF_GET_OBJECT(userToken);
     //            NSLog(@"token==%@",token);
     
         
        instance.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", @"image/jpeg",@"image/png", @"application/octet-stream", nil];
        //            instance.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        
        [instance.requestSerializer setValue:token forHTTPHeaderField:@"accessToken"];

        NSDictionary * dict = [self.para toDictionary];
        
        NSLog(@"==%@",dict);
        
        [instance POST:@"data/updateUrgentContactInfo.json" parameters:[self.para toDictionary] progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if([[responseObject objectForKey:@"code"]intValue]==0)
            {
                //            [self showHint:@"保存成功"];
                //            [self.navigationController popViewControllerAnimated:YES];
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:@"保存成功"
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          //响应事件
                                                                          [self.navigationController popViewControllerAnimated:YES];
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                [self showHint:[responseObject objectForKey:@"message"]];
                
                
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self showHint:@"网络错误"];
        }];
        
//    [[NetworkTool manager] POST:[Interfacefile updateUrgentContactInfo] Param:dict andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
////        NSLog(@"res++%@",responseObject);
//        if([[responseObject objectForKey:@"code"]intValue]==0)
//        {
////            [self showHint:@"保存成功"];
////            [self.navigationController popViewControllerAnimated:YES];
//            
//            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
//                                                                           message:@"保存成功"
//                                                                    preferredStyle:UIAlertControllerStyleAlert];
//            
//            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
//                                                                  handler:^(UIAlertAction * action) {
//                                                                      //响应事件
//                                                                      [self.navigationController popViewControllerAnimated:YES];
//                                                                  }];
//            
//            [alert addAction:defaultAction];
//            [self presentViewController:alert animated:YES completion:nil];
//        }else{
//            
//            [self showHint:[responseObject objectForKey:@"message"]];
//            
//            
//        }
//    } andFailure:^(NSError * _Nonnull error) {
//        [self showHint:@"网络错误"];
//    }];
    }];

}


- (void)backToLastView{
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIButton *)setBackButton{
    
    UIButton * button = [UIButton new];
    
    [button addTarget:self action:@selector(didSelectedButton:) forControlEvents:UIControlEventTouchUpInside];
    button.backgroundColor = [UIColor clearColor];
    
    return button;
    
}


- (void)didSelectedButton:(UIButton *)button{
    
    NSString * Authorized;
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    switch (status) {
        case CNAuthorizationStatusAuthorized:
        {
//            NSLog(@"Authorized:");
            Authorized = @"Authorized";
        } break;
        case CNAuthorizationStatusDenied:
        {
//            NSLog(@"Denied");
            Authorized = @"Denied";
        } break;
        case CNAuthorizationStatusRestricted:
        {
//            NSLog(@"Restricted");
            Authorized = @"Restricted";
        } break;
        case CNAuthorizationStatusNotDetermined:
        {
//            NSLog(@"NotDetermined");
            Authorized = @"NotDetermined";
        } break;
    }
    
    
//    if ([Authorized isEqualToString:@"Authorized"] || [Authorized isEqualToString:@"NotDetermined"]) {
    
        switch (button.tag) {
            case 0:
            {
                if(self.typePageModel)
                {
                    [[WSZCustomPickView standViewWithDataArr:self.typePageModel.familyRelationEnum Task:^(NSInteger index, id model) {
                        MemberInfoTypeModel * type = model;
                        if (index == 0) {
                            self.para.familyContactType = @6;
                        }else if (index == 1){
                            
                            self.para.familyContactType = @7;
                        }else{
                            self.para.familyContactType = @(index - 2);
                        }
                        
//                        self.familyContactType = [NSString stringWithFormat:@"%ld",(long)index];
                        self.relationField.text = type.name;
                        
                    }] show];
                }else
                {
                    [self getTypeModel:^{
                        [[WSZCustomPickView standViewWithDataArr:self.typePageModel.familyRelationEnum Task:^(NSInteger index, id model) {
                            MemberInfoTypeModel * type = model;
                            if (index == 0) {
                                self.para.familyContactType = @6;
                            }else if (index == 1){
                                
                                self.para.familyContactType = @7;
                            }else{
                                self.para.familyContactType = @(index - 2);
                            }
//                            self.familyContactType = [NSString stringWithFormat:@"%ld",(long)index];
                            self.relationField.text = type.name;
                            
                        }] show];
                        
                    }];
                }
            }
                break;
            case 1:
            {
                if ([Authorized isEqualToString:@"Authorized"] || [Authorized isEqualToString:@"NotDetermined"]) {
                [self accessTheContact];
                [self setSelectBlock:^(NSString *tel, NSString *name) {
                    self.para.familyContactName = name;
//                    self.familyContactName = [NSString stringWithFormat:@"%@",name];
                    self.para.familyContactTel = tel;
//                    self.familyContactTel = [NSString stringWithFormat:@"%@",tel];
                    self.contractField.text = name;
                    
                }];
                }else{
                    
                    [self showHint:@"请先获取访问权限！"];
                }
            }
                break;
            case 2:
            {
                if(self.typePageModel)
                {
                    [[WSZCustomPickView standViewWithDataArr:self.typePageModel.urgencyRelationEnum Task:^(NSInteger index, id model) {
                        MemberInfoTypeModel * type = model;
                        self.para.urgencyContactType = @(index);
//                        self.urgencyContactType = [NSString stringWithFormat:@"%ld",(long)index];
                        self.bottomRelationField.text = type.name;
                        
                    }] show];
                }else
                {
                    [self getTypeModel:^{
                        [[WSZCustomPickView standViewWithDataArr:self.typePageModel.addressSpanEnum Task:^(NSInteger index, id model) {
                            MemberInfoTypeModel * type = model;
                            self.para.urgencyContactType = @(index);
//                            self.urgencyContactType = [NSString stringWithFormat:@"%ld",(long)index];
                            self.bottomRelationField.text = type.name;
                        }] show];
                        
                    }];
                }
            }
                break;
            case 3:
            {
                if ([Authorized isEqualToString:@"Authorized"] || [Authorized isEqualToString:@"NotDetermined"]) {
                [self accessTheContact];
                
                [self setSelectBlock:^(NSString *tel, NSString *name) {                    
                    
                    if([self.contractField.text isEqualToString:name]){
                        
                        [self showHint:@"直系亲属联系人与常用联系人不可重复。"];
                    }else{
                       self.bottonContractField.text = name;
                        self.para.urgencyContactName = name;
//                        self.urgencyContactName = [NSString stringWithFormat:@"%@",name];
                        self.para.urgencyContactTel = tel;
//                        self.urgencyContactTel = [NSString stringWithFormat:@"%@",tel];
                    }
                    
                    
                    
                }];
                }else{
                    
                    [self showHint:@"请先获取访问权限！"];
                }
            }
                break;
            default:
                break;
        }
//    }else{
//        
//        [self showHint:@"请先获取访问权限！"];
//    }
    
    
}


- (UILabel *)setupLabelWith:(NSString *)title{
    
    UILabel * label = [UILabel new];
    
    label.textColor = ColorWithRGB(0x303c41);
    label.font = [UIFont systemFontOfSize:13.5 * SCREENH6];
    label.text = title;
    
    return label;
}



-(UITextField*)setUpTextfieldWithString:(NSString*)text
{
    UITextField * textField = [UITextField new];
    textField.borderStyle = UITextBorderStyleNone;
    textField.backgroundColor = [UIColor clearColor];
    textField.layer.borderColor = [[UIColor clearColor] CGColor];
    textField.textAlignment = NSTextAlignmentRight;
    //设置光标颜色
    textField.tintColor = ColorWithRGB(0xcecece);
    //修改占位符文字颜色
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSForegroundColorAttributeName] = ColorWithRGB(0xcecece);
//    attrs[NSFontAttributeName] = [UIFont fontWithName:@"PingFangSC-Regular" size:12 * SCREENH6];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:12 * SCREENH6];
    //修改占位符文字颜色
    textField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:text attributes:attrs];
    textField.textColor = ColorWithRGB(0x303c41);
    textField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 22 * SCREENH6, 0)];
    //设置显示模式为永远显示(默认不显示)
    textField.leftViewMode = UITextFieldViewModeAlways;
//    textField.font = [UIFont fontWithName:@"PingFangSC-Regular" size:13 * SCREENH6];
    textField.font = [UIFont systemFontOfSize:12 * SCREENH6];
    return textField;
}


- (UIButton *)setupTitleButtonWith:(NSString *)string{
    
    UIButton * button = [UIButton new];
    
    [button setTitleColor:ColorWithRGB(0xcecece) forState:UIControlStateNormal];
//    [button addTarget:self action:@selector(didSelectedButton:) forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:13 * SCREENH6];
    button.userInteractionEnabled = NO;
    
    return button;
}


- (UIImageView *)setupRightImage{
    
    UIImageView * imageView = [UIImageView new];
    
    imageView.image = [UIImage imageNamed:@"返回-拷贝-6"];
    
    return imageView;
}


- (UIView *)setupLineView{
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xdbdbdb);
    
    return lineView;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/** 系统授权访问通讯录*/

- (void) accessTheContact{
    
    ABAddressBookRef addressBook = nil;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 6.0) {
        addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
        dispatch_semaphore_t sem = dispatch_semaphore_create(0);
        ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
                [self presentSystemContact];

        });
    }else{
        addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
    }
}




-(void)upLoadAddressBookComplete:(void(^)())complete
{
    [[HDAddressBookTool shareTool]initialAddressBookSuccess:^(NSArray *addressBook) {
        __block NSMutableArray*addresses = [NSMutableArray array];
        [addressBook enumerateObjectsUsingBlock:^(HDAddressBookPersonModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [addresses addObject:[obj toDictionary]];
        }];
        
//        NSLog(@"array==%@",addresses.copy);
        
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURL * url = [NSURL URLWithString:@"http://api.xianjinedai.com/"];
        //        NSURL * url = [NSURL URLWithString:@"http://106.14.157.18:8080/"];
        //1.实例化
        AFHTTPSessionManager * instance = [[AFHTTPSessionManager alloc] initWithBaseURL:url sessionConfiguration:configuration];
        
        
        //2.可接受格式
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",@"image/jpeg",@"text/plain", nil];
        
        
        //4.超时
        instance.requestSerializer.timeoutInterval = 10.0;
        instance.requestSerializer = [AFJSONRequestSerializer serializer];
        
        NSString * token = DEF_GET_OBJECT(userToken);
        //            NSLog(@"token==%@",token);
        
        
        instance.requestSerializer.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
        [instance.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        instance.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/javascript",@"text/html", @"image/jpeg",@"image/png", @"application/octet-stream", nil];
        //            instance.requestSerializer = [AFHTTPRequestSerializer serializer];
        
        
        [instance.requestSerializer setValue:token forHTTPHeaderField:@"accessToken"];
        
        [instance POST:@"data/uploadUserContactList.json" parameters:addresses.copy progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if([[responseObject objectForKey:@"code"]intValue]==0)
            {
                complete();
            }else{
                
                [self showHint:[responseObject objectForKey:@"message"]];
                
                
            }        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self showHint:@"网络错误"];
        }];
        
//        [[NetworkTool shareManager] POSTJson:[Interfacefile uploadUserContactList] Param:addresses.copy andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
//            if([[responseObject objectForKey:@"code"]intValue]==0)
//            {
//                complete();
//            }else{
//                
//                [self showHint:[responseObject objectForKey:@"message"]];
//                
//                
//            }
//        } andFailure:^(NSError * _Nonnull error) {
//            [self showHint:@"网络错误"];
//        }];
        
    }];
}



/** 调用系统通讯录*/

- (void) presentSystemContact{
    
    NSString * Authorized;
    CNAuthorizationStatus status = [CNContactStore authorizationStatusForEntityType:CNEntityTypeContacts];
    switch (status) {
        case CNAuthorizationStatusAuthorized:
        {
            //            NSLog(@"Authorized:");
            Authorized = @"Authorized";
        } break;
        case CNAuthorizationStatusDenied:
        {
            //            NSLog(@"Denied");
            Authorized = @"Denied";
        } break;
        case CNAuthorizationStatusRestricted:
        {
            //            NSLog(@"Restricted");
            Authorized = @"Restricted";
        } break;
        case CNAuthorizationStatusNotDetermined:
        {
            //            NSLog(@"NotDetermined");
            Authorized = @"NotDetermined";
        } break;
    }
    
    if ([Authorized isEqualToString:@"Authorized"] || [Authorized isEqualToString:@"NotDetermined"]) {
        
        ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc]init];
        peoplePicker.peoplePickerDelegate = self;
        [self presentViewController:peoplePicker animated:YES completion:^{
            
        }];
        
    }else{
        
        [self showHint:@"请先获取访问权限！"];
    }

    
    
}

/** 通讯录代理方法*/

- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person{
    
    
    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,0);
    CFStringRef telvalue = ABMultiValueCopyValueAtIndex(valuesRef, index);
    CFStringRef anFullname = ABRecordCopyCompositeName(person);
    
    [self dismissViewControllerAnimated:YES completion:^{
//        NSLog(@"tel --- %@,name -- %@",telvalue,anFullname);
        self.selectBlock( (__bridge NSString *)telvalue, (__bridge NSString *)anFullname);
        
    }];
    
}

//- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
//    
//    NSLog(@"==%d",identifier);
//    
//    ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
//    CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier );
//    CFStringRef telvalue = ABMultiValueCopyValueAtIndex(valuesRef, index);
//    CFStringRef anFullname = ABRecordCopyCompositeName(person);
//    
//    [self dismissViewControllerAnimated:YES completion:^{
//        NSLog(@"tel --- %@,name -- %@",telvalue,anFullname);
//        self.selectBlock( (__bridge NSString *)telvalue, (__bridge NSString *)anFullname);
//
//    }];
//}




-(void)getPageModel
{
    if (self.currentStep > 2) {
        
        ParaModel*para = [ParaModel new];
        
        
        [[NetworkTool shareManager] POST:[Interfacefile loadCurrentPersonalInfo] Param:[para toDictionary] andWaitStr:@"" waitView:self.view success:^(id  _Nullable responseObject) {
            if([[responseObject objectForKey:@"code"]intValue]==0)
            {
                self.pageModel = [[MemberInfoModel alloc] initWithDictionary:[responseObject objectForKey:@"data"] error:nil];
                self.para.familyContactType = self.pageModel.familyRelation;
                self.para.familyContactName = self.pageModel.familyContact;
                self.para.familyContactTel = self.pageModel.familyTel;
                self.para.urgencyContactType = self.pageModel.urgencyRelation;
                self.para.urgencyContactName = self.pageModel.urgencyContact;
                self.para.urgencyContactTel = self.pageModel.urgencyTel;
                [self getTypeModel:nil];
                
            }else{
                
                [self showHint:[responseObject objectForKey:@"message"]];
                
                
            }
        } andFailure:^(NSError * _Nonnull error) {
            [self showHint:@"网络错误"];
        }];
    }
    
    
}

-(void)getTypeModel:(void(^)())complete
{
    ParaModel*para = [ParaModel new];
    
    
    [[NetworkTool manager] POST:[Interfacefile loadUserRelatedEnums] Param:[para toDictionary] andWaitStr:@"" waitView:nil success:^(id  _Nullable responseObject) {
        
        if([[responseObject objectForKey:@"code"]intValue]==0)
        {
            self.typePageModel = [[MemberInfoTypePageModel alloc] initWithDictionary:[responseObject objectForKey:@"data"] error:nil];
            if(complete)
            {
                complete();
            }else
            {
                [self updateView];
            }
        }else{
            if(complete)
                [self showHint:[responseObject objectForKey:@"message"]];
            
            
        }
    } andFailure:^(NSError * _Nonnull error) {
        if(complete)
            [self showHint:@"网络错误"];
    }];
    
}

-(ParaModel*)para
{
    if(!_para)
    {
        _para = [ParaModel new];
    }
    return _para;
}





-(void)updateView
{
    [self.typePageModel.familyRelationEnum enumerateObjectsUsingBlock:^(MemberInfoTypeModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if(self.pageModel.familyRelation&& ([obj.value integerValue]==[self.pageModel.familyRelation intValue]))
        {
            self.relationField.text = obj.name;
        }
    }];
    [self.typePageModel.urgencyRelationEnum enumerateObjectsUsingBlock:^(MemberInfoTypeModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if(self.pageModel.urgencyRelation&& ([obj.value integerValue]==[self.pageModel.urgencyRelation intValue]))
        {
            self.bottomRelationField.text = obj.name;
        }
    }];
    self.contractField.text = self.pageModel.familyContact;
    self.bottonContractField.text = self.pageModel.urgencyContact;
}





@end
